#!/bin/bash

# erase-install postinstall script
# install swiftDialog and mist-cli if not already present

# current directory
DIR=$(dirname "$0")

# swiftDialog - required version depends on macOS version
system_version=$( /usr/bin/sw_vers -productVersion )

# macOS 12 and greater uses the latest swiftDialog
system_os=$(/usr/bin/cut -d. -f 1 <<< "$system_version")

if [[ $system_os -ge 12 ]]; then
    if [[ -d "/Library/Management/erase-install/Dialog.app" ]]; then
        echo "swiftDialog successfully installed"
    else
        echo "ERROR: swiftDialog was not installed"
        exit 1
    fi
elif [[ $system_os -eq 11 ]]; then
    if /usr/sbin/installer -tgt / -pkg "$DIR/swiftDialog-bigsur.pkg"; then
        echo "swiftDialog (Big Sur version) successfully installed"
    else
        echo "ERROR: swiftDialog was not installed"
        exit 1
    fi
else
    echo "ERROR: swiftDialog not compatible with this version of macOS"
    exit 1
fi

# mist-cli
if /usr/sbin/installer -tgt / -pkg "$DIR/mist-cli.pkg"; then
    echo "mist-cli successfully installed"
else
    echo "ERROR: mist-cli was not installed"
    exit 1
fi

# jq
if [[ $system_os -le 14 && ! -f /usr/local/bin/jq ]]; then
    # check if the mac is arm64 or intel
    arch=$(/usr/bin/uname -m)
    if [[ $arch == "arm64" ]]; then
        jq_source="$DIR/jq-arm64"
    else
        jq_source="$DIR/jq-amd64"
    fi

    if /bin/cp "$jq_source" /usr/local/bin/jq; then
        /bin/chmod +x /usr/local/bin/jq
        echo "jq successfully installed"
    else
        echo "ERROR: jq was not installed"
        exit 1
    fi
fi

